import { Todo, ITodo } from '../scripts/types.js'

let _todos = localStorage.getItem('todos')
if (_todos) {
  try {
    // 缓存中的数据只有 content、finished 属性，没有el，对应的是ITodo接口而不是Todo
    var itodos: ITodo[] = JSON.parse(_todos)
    var localtodos=[]
    for (let item of itodos) {
      let todo = new Todo(item)
      localtodos.push(todo)
    }
  } catch (error) {
    console.error('invalid cache')
  }
}
function dump(todos) {
  localStorage.setItem('todos', JSON.stringify(todos))
}

interface State {
  todos: Todo[]
}
class ToDoList extends React.Component<any, State> {
    state:State= {
      todos:localtodos
    }

  addItem(item: Todo) {
    this.state.todos.push(item)
    console.log(item);
    dump(this.state.todos)
    this.setState({
      todos:this.state.todos
    })
  }

  toggleItem(item:Todo,index){
    item.finished = !item.finished
    this.state.todos[index]=item
    this.setState({
      todos:this.state.todos
    })
    dump(this.state.todos)
  }

  delItem(item:Todo){
    let index=this.state.todos.indexOf(item)
    this.state.todos.splice(index,1)
    this.setState({
      todos:this.state.todos
    })
    dump(this.state.todos)
  }

  render() {
    return (
      <React.Fragment>
        <header>
          <div className="title">TS Todo</div>
          <input
            id="input"
            type="text"
            className="input"
            placeholder="What needs to be done?"
            autoComplete="off"
            ref="todoinput"
            onKeyDown={(event)=>{
              let value = this.refs.todoinput.value
              if (event.key === 'Enter' && value !== '') {
              let todo = new Todo({ content: value, finished: false })
              this.addItem(todo)
              this.refs.todoinput.value=''
              }
            }}
          />
        </header>
        <section id="todos">
          {
          this.state.todos.map((todo,index) => {
            console.log(this.state.todos);
            return (
              <div className={todo.finished?"todo-item todo-finished":"todo-item"} key={index}>
              <i 
              className="iconfont icon-checkbox"
              onClick={()=>this.toggleItem(todo,index)}
              ></i>
              <span className="todo-title">{todo.content}</span>
              <i 
              className="iconfont icon-delete"
              onClick={()=>this.delItem(todo)}
              ></i>
            </div>
          )
            
          })
          }
        </section>
      </React.Fragment>
    )
  }
}

ReactDOM.render(<ToDoList />, document.getElementById('app'))
